package com.lb.bs.client.repository;

import com.lb.bs.client.annotation.LBClass;
import com.lb.bs.client.annotation.LBUpdateClass;
import com.lb.bs.client.callback.UpdateCallBackService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * program: LB-BS-Client
 * author: bsworld.xie
 * create: 2020-05-18 15:44
 * description:
 */
public class BeanHolder<T> {

    private static BeanHolder holder;

    private volatile Map<Class<T>, T> clazzMap = new HashMap<>();

    private Map<String, T> nameMap = new HashMap<>();

    /**
     * key原始bean class
     * <p>
     * value:代理类的对象
     */
    private Map<Class<T>, T> proxyMap = new HashMap<>();
    /**
     *
     * {@link LBClass 注解的bean}
     * */
    private List<Object> commonBean = new ArrayList<>();
    /**
     *
     * {@link LBUpdateClass 注解的bean}
     *
     * */
    private List<UpdateCallBackService> updateCallBackBean = new ArrayList<>();

    public <T> T getBean(Class<T> clazz) {
        T t = (T) clazzMap.get(clazz);
        return t;
    }


    public T getBean(String name) {
        return nameMap.get(name);
    }


    public T getProxyBeanByOriginClazzType(Class<?> originClazz) {
        T t = proxyMap.get(originClazz);
        return t;
    }

    public void registerBean(Class<T> clazz, T t) {
        String simpleName = clazz.getSimpleName();
        clazzMap.put(clazz, t);
        nameMap.put(simpleName, t);
    }

    public void registerProxy(Class<T> originClazz, T proxyBean) {
        proxyMap.put(originClazz, proxyBean);
    }


    public static <T> BeanHolder<T> getHolder() {
        if (holder == null) {
            synchronized (BeanHolder.class) {
                if (holder == null) {
                    holder = new BeanHolder();
                }
            }
        }
        return holder;
    }


    public void registerLbClassBean(T bean) {
        commonBean.add(bean);
    }

    public List<Object> getCommonBean() {
        return commonBean;
    }

    public void  registerLbUpdateBean(UpdateCallBackService t) {
        updateCallBackBean.add(t);
    }

    public List<UpdateCallBackService> getUpdateCallBackBean() {
        return updateCallBackBean;
    }

    private BeanHolder() {

    }
}
